﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SqlServer.Server;


public class StoredProcedures
{
    [SqlProcedure()]
    public static Int32 FilterExists(SqlGuid feedId, SqlBinary feedItems)
    {
        if (feedId.IsNull)
            throw new ArgumentNullException("feedId");
        if (feedItems.IsNull)
            throw new ArgumentNullException("feedItems");
        var deserialized = BinaryToGuids(feedItems);
        var feedItemList = deserialized as List<Guid> ?? new List<Guid>(deserialized);

        using (var connection = new SqlConnection("context connection=true"))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = "SELECT COUNT(*) FROM FeedItem WHERE LocalId = @LocalId AND FeedId=@FeedId";
                command.Parameters.AddWithValue("@FeedId", feedId);
                command.Parameters.Add("@LocalId", SqlDbType.UniqueIdentifier);
                foreach (var feedItemId in feedItemList.ToArray())
                {
                    command.Parameters["@LocalId"].Value = feedItemId;
                    var count = (int)command.ExecuteScalar();
                    if (count != 0)
                        feedItemList.Remove(feedItemId);
                }
            }
            var column = new SqlMetaData("FeedId", SqlDbType.UniqueIdentifier);
            var row = new SqlDataRecord(column);
            SqlContext.Pipe.SendResultsStart(row);
            foreach (var guid in feedItemList)
            {
                row.SetGuid(0, guid);
                SqlContext.Pipe.SendResultsRow(row);        
            }
            SqlContext.Pipe.SendResultsEnd();
            return 0;
        }
    }
    private static IEnumerable<Guid> BinaryToGuids(SqlBinary feeds)
    {
        var feedIdBytes = new byte[16];
        for (int i = 0; i < feeds.Length; i += 16 )
        {
            Array.Copy(feeds.Value, i, feedIdBytes, 0, 16);
            yield return new Guid(feedIdBytes);
        }
    }
};
